from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.response import Response
from rest_framework_simplejwt.views import TokenViewBase
from rest_framework.decorators import authentication_classes, permission_classes
from app.serializers import MyTokenSerializer
from app.middleware import CustomJsonRender
User = get_user_model()
# 自定义的登陆视图

@authentication_classes([])
@permission_classes([])

class LoginView(TokenViewBase):
    serializer_class = MyTokenSerializer  # 使用刚刚编写的序列化类
    # renderer_classes = (CustomJsonRender)
    # post方法对应post请求，登陆时post请求在这里处理
    def post(self, request, *args, **kwargs):
        username = request.data.get('username')  # 获取用户名
        password = request.data.get('password')  # 获取密码
        # 校验用户名和密码是否正确
        if not username or not password:
            raise ValueError('用户名和密码不能为空')
        # 使用刚刚编写时序列化处理登陆验证及数据响应
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            raise ValueError(f'验证失败： {e}')
        
        return Response(serializer.validated_data, status=status.HTTP_200_OK)


